package org.jflame.uid.segment.dao.impl;

import org.jflame.uid.segment.dao.IDAllocDao;
import org.jflame.uid.segment.model.LeafAlloc;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

/**
 * 基于原生jdbc实现IDAllocDao,不依赖第三方框架
 */
public class IDAllocJdbcImpl implements IDAllocDao {

    private JdbcTemplate jdbcTemplate;

    public IDAllocJdbcImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    private static final String SQL_QUERY_ALL_LEAFALLOC = "SELECT biz_tag, max_id, step, update_time FROM leaf_alloc";

    @Override
    public List<LeafAlloc> getAllLeafAllocs() {
        return jdbcTemplate.query(SQL_QUERY_ALL_LEAFALLOC, BeanPropertyRowMapper.newInstance(LeafAlloc.class));
    }

    private static final String SQL_UPDATEMAXID = "UPDATE leaf_alloc SET max_id = max_id + step WHERE biz_tag = ?";
    private static final String SQL_GET_LEAFALLOC = "SELECT biz_tag, max_id, step FROM leaf_alloc WHERE biz_tag = ?";

    @Override
    @Transactional
    public LeafAlloc updateMaxIdAndGetLeafAlloc(String tag) {
        jdbcTemplate.update(SQL_UPDATEMAXID, tag);
        return jdbcTemplate.queryForObject(SQL_GET_LEAFALLOC, new Object[] { tag },
                BeanPropertyRowMapper.newInstance(LeafAlloc.class));
    }

    private static final String SQL_UPDATEMAXID_BYSTEP = "UPDATE leaf_alloc SET max_id = max_id + ? WHERE biz_tag = ?";

    @Override
    @Transactional
    public LeafAlloc updateMaxIdByCustomStepAndGetLeafAlloc(LeafAlloc leafAlloc) {
        jdbcTemplate.update(SQL_UPDATEMAXID_BYSTEP, new Object[] { leafAlloc.getStep(),leafAlloc.getKey() });
        return jdbcTemplate.queryForObject(SQL_GET_LEAFALLOC, new Object[] { leafAlloc.getKey() },
                BeanPropertyRowMapper.newInstance(LeafAlloc.class));
    }

    private static final String SQL_QUERY_ALL_TAG = "SELECT biz_tag FROM leaf_alloc";

    @Override
    public List<String> getAllTags() {
        return jdbcTemplate.queryForList(SQL_QUERY_ALL_TAG, String.class);
    }

}
